//
//  detailMessageViewController.m
//  TTAddressBook
//
//  Created by 贾政阳 on 12-1-6.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "detailMessageViewController.h"
#define TABLEVIEWTAG	300
#define DELVIEW_TAG 400
@implementation detailMessageViewController
@synthesize strMark, table, messageArray;

#pragma mark Table view methods
- (UIView *)bubbleView:(NSString *)text from:(BOOL)fromSelf {
	// build single chat bubble cell with given text
	UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
	returnView.backgroundColor = [UIColor clearColor];
    
	UIImage *bubble = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fromSelf?@"bubbleSelf":@"bubble" ofType:@"png"]];
    
	UIImageView *bubbleImageView = [[UIImageView alloc] initWithImage:[bubble stretchableImageWithLeftCapWidth:21 topCapHeight:14]];
    
	UIFont *font = [UIFont systemFontOfSize:12];
	CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(150.0f, 1000.0f) lineBreakMode:UILineBreakModeCharacterWrap];
    
	UILabel *bubbleText = [[UILabel alloc] initWithFrame:CGRectMake(21.0f, 0.0f, size.width+5, size.height+5)];
	bubbleText.backgroundColor = [UIColor clearColor];
	bubbleText.font = font;
	bubbleText.numberOfLines = 0;
	bubbleText.lineBreakMode = UILineBreakModeCharacterWrap;
	bubbleText.text = text;
	
	bubbleImageView.frame = CGRectMake(0.0f, 0.0f, size.width+40, size.height+10.0f);
    int ileft=0;
    if (showChoose) {
        ileft=30;
    }
	if(fromSelf)
    {
		returnView.frame = CGRectMake(130.0f, 20.0f, 180.f, size.height+10.0f);
        bubbleText.frame = CGRectMake(160-size.width, 0.0f, size.width+5, size.height+5);
        bubbleImageView.frame = CGRectMake(145-size.width, 0.0f, size.width+35, size.height+10.0f);
    }
	else
		returnView.frame = CGRectMake(10.0f+ileft, 20.0f, 180.f, size.height+10.0f);
	
	[returnView addSubview:bubbleImageView];
	[bubbleImageView release];
	[returnView addSubview:bubbleText];
	[bubbleText release];
    
	return [returnView autorelease];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView.contentOffset.y+scrollView.frame.size.height-40 > scrollView.contentSize.height) {
        NSMutableArray * arr=[[NSMutableArray alloc] init];
        NSDictionary * ret = [[MyClass getInstance] getNewMessages:strMark startAt:startAt limit:15];
        if ([[ret objectForKey:@"total"] intValue] > 0) {
            arr = [ret objectForKey:@"list"];
            
            if (arr) {
                startAt = startAt + [arr count];
                [self.messageArray addObjectsFromArray:arr];
            }
        }

    }
    else if (scrollView.contentOffset.y < -20){
        //NSLog(@"往上啦");
        NSDictionary * ret = [[MyClass getInstance] getNewMessages:0 startAt:startAt limit:15];
        if ([[ret objectForKey:@"total"] intValue] > 0) {
            self.messageArray = [ret objectForKey:@"list"];
            if (messageArray) {
                startAt = [messageArray count];
            }
        }
    }
}
-(id)initWithContactID:(NSString*)contactName{
    self = [self init];
    if (self) {
        self.strMark = contactName;
        MyClass *gs = [MyClass getInstance];
        NSDictionary * ret = [gs getNewMessages:contactName startAt:startAt limit:15];
        if ([[ret objectForKey:@"total"] intValue] > 0) {
            NSArray * arr = [ret objectForKey:@"list"];
            if (self.messageArray ) {
                [self.messageArray removeAllObjects];
            }
            else
            {
                self.messageArray= [[NSMutableArray alloc] init];   
                [self.messageArray addObjectsFromArray:arr];
                startAt+=[arr count];
            }
        }
    }
    if ([messageArray count]<=0)
        self.title  = @"往来消息";
    else
         self.title = [[messageArray objectAtIndex:0] objectForKey:@"personShowName"];
    [self setHidesBottomBarWhenPushed:YES];
        return self;
}

-(id)initWithOneContact:(NSDictionary*)contactDic{
    self = [self init];
    if (self) {
        oneContact = [[NSDictionary  alloc] initWithDictionary:contactDic];
        self.strMark = [oneContact objectForKey:@"personMark"];
    }
//        MyClass *gs = [MyClass getInstance];
//        NSDictionary * ret = [gs getNewMessages:self.strMark startAt:startAt limit:15];
//        if ([[ret objectForKey:@"total"] intValue] > 0) {
//            NSArray * arr = [ret objectForKey:@"list"];
//            if (self.messageArray ) {
//                [self.messageArray removeAllObjects];
//            }
//            else
//            {
//                self.messageArray= [[NSMutableArray alloc] init];   
//                [self.messageArray addObjectsFromArray:arr];
//                startAt+=[arr count];
//            }
//        }
//    }
//    if ([messageArray count]<=0)
//        self.title  = @"往来消息";
//    else
//        self.title = [[messageArray objectAtIndex:0] objectForKey:@"personShowName"];
    [self setHidesBottomBarWhenPushed:YES];
    return self;
}

-(id)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}

-(void)dealloc{
    self.strMark = nil;
    self.messageArray = nil;
    [oneContact release];
    [popTipView release];
    [containerView release];
    [textView release];
    
    self.table = nil;
    [super dealloc];
}


-(void)popToRootView{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark 编辑信息功能 删除信息内容

- (void)resetUI{
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(popToRootView)] autorelease];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleBordered target:self action:@selector(setTableEdit:)] autorelease];
   // [self.table setEditing:NO animated:YES];
    
    UIView* delView = [self.view viewWithTag:DELVIEW_TAG];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.5];
    
    containerView.frame = CGRectMake(0, self.view.frame.size.height - 40, 320, 40);
    delView.frame = CGRectMake(0, self.view.frame.size.height, 320, 40);
    
    [UIView commitAnimations];
}

- (void)cancelAction:(id)sender
{
    // leave edit mode for our table and apply the edit button
    [self resetUI];
    showChoose= NO;
    [table reloadData];
}
//
- (void)delAllSms:(id)sender{
    delAll= YES;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@" " 
                                                             delegate:self
                                                    cancelButtonTitle:@"取消" 
                                               destructiveButtonTitle:@"清空信息内容" 
                                                    otherButtonTitles:nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	[actionSheet showInView:self.tabBarController.view];	// show from our table view (pops up in the middle of the table)
	[actionSheet release];}
- (void) setTableEdit:(id)sender{
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelAction:)] autorelease];
    showChoose= YES;
    [table reloadData];
    
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"删除全部" style:UIBarButtonItemStyleBordered target:self action:@selector(delAllSms:)] autorelease];
    
//    [self.table setEditing:YES animated:YES];
    
    [self resignTextView];

    UIView* delView = [self.view viewWithTag:DELVIEW_TAG];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.5];
    
    containerView.frame = CGRectMake(0, self.view.frame.size.height, 320, 40);
    delView.frame = CGRectMake(0, self.view.frame.size.height-40, 320, 40);
    
    [UIView commitAnimations];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	// the user clicked one of the OK/Cancel buttons
	if (buttonIndex == 0)
	{
		// delete the selected rows
        if (!delAll)
        {
            @try {
                NSMutableArray * arr =[[NSMutableArray alloc] init]; 
                NSMutableArray * newArr =[[NSMutableArray alloc] init]; 
                for (NSDictionary *dict in messageArray) {
                    if ([[dict objectForKey:@"check"] isEqualToString:@"true"])
                        [arr addObject:[dict objectForKey:@"id"]];
                    else {
                        [newArr addObject:dict];
                    }
                }
                if ([[[[MyClass getInstance] delMessages:arr] objectForKey:@"code"] intValue]==0){
                    self.messageArray = newArr;
                }
                else
                {
                    UIAlertView* alert;
                    alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"删除失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alert show];
                    [alert release];
                }
                [arr release];
                [newArr release];
            }
            @catch (NSException *exception) {
                UIAlertView* alert;
                alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"删除失败!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                [alert release];
            }
            @finally {
                
            }
            [self.table reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
            
        }
        else
        {
            
            @try {
                NSMutableArray * arr =[[NSMutableArray alloc] init];                                      
                for (NSDictionary *dict in messageArray) {
                    [arr addObject:[dict objectForKey:@"id"]];
                }
                if ([[[[MyClass getInstance] delMessages:arr] objectForKey:@"code"] intValue]==0){
                    [self.messageArray removeAllObjects];
                }else
                {
                    UIAlertView* alert;
                    alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"删除失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alert show];
                    [alert release];
                } 
                [arr release];
            }
            @catch (NSException *exception) {
                UIAlertView* alert;
                alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"删除失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                [alert release];
            }
            @finally {
                
            }
            
            // since we are deleting all the rows, just reload the current table section
            [self.table reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        showChoose = NO;
        [table reloadData];
        [self resetUI]; // reset our UI
        [self.table setEditing:NO animated:YES];
        
        self.navigationItem.leftBarButtonItem.enabled = (self.messageArray.count > 0) ? YES : NO;
	}
}

-(void)delSomeSms:(id)sender{
    delAll=NO;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@" " 
                                                             delegate:self 
                                                    cancelButtonTitle:@"取消" 
                                               destructiveButtonTitle:@"删除对话内容" 
                                                    otherButtonTitles:nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	[actionSheet showInView:self.tabBarController.view];	// show from our table view (pops up in the middle of the table)
	[actionSheet release];
}

-(void) creatDelView{
    extern double  globalRed,globalGreen,globalBlue;
    UIView* delView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, 320, 40)];
    delView.tag = DELVIEW_TAG;
    btnDelSms = [UIButton buttonWithType:UIButtonTypeCustom];
    btnDelSms.frame = CGRectMake(40, 7, 100, 25);
    btnDelSms.backgroundColor =[UIColor colorWithRed:globalRed/255 green:globalGreen blue:globalBlue/255 alpha:1.0];
    btnDelSms.layer.cornerRadius = 10;/////////////////////////自己试着改变这个值，看看各个不同的效果。现在的设置是画了个圆圈。
    btnDelSms.layer.masksToBounds = YES;//////////////////////////  
    [btnDelSms setTitle:@"删除短信" forState: UIControlStateNormal];
    btnDelSms.titleLabel.font = [UIFont systemFontOfSize:11];
    [btnDelSms addTarget:self action:@selector(delSomeSms:) forControlEvents:UIControlEventTouchUpInside];    
    [delView addSubview:btnDelSms];

    btnSendSms = [UIButton buttonWithType:UIButtonTypeCustom];
    btnSendSms.frame = CGRectMake(170, 7, 100, 25);
    [btnSendSms setTitle: @"转发短信" forState:(UIControlStateNormal)];
    btnSendSms.backgroundColor =[UIColor colorWithRed:globalRed/255 green:globalGreen blue:globalBlue/255 alpha:1.0];
    btnSendSms.titleLabel.font = [UIFont systemFontOfSize:11];
    [btnSendSms addTarget:self action:@selector(transmitMessage) forControlEvents:UIControlEventTouchUpInside];    
    btnSendSms.layer.cornerRadius = 10;/////////////////////////自己试着改变这个值，看看各个不同的效果。现在的设置是画了个圆圈。
    btnSendSms.layer.masksToBounds = YES;//////////////////////////  
    [delView addSubview: btnSendSms];
    [self.view addSubview:delView];
    [delView release];
    
}
#pragma mark - View lifecycle
-(void) goToComposeMsg{
    [MyClass getInstance].PersonMarkList = nil;
    if ([MyClass getInstance].personMarkList) {
        [[MyClass getInstance].personMarkList removeAllObjects];
    }
    else
    {
        [MyClass getInstance].personMarkList = [[NSMutableArray alloc] init];
    }
    
    NSMutableArray* arrCheckList=[[NSMutableArray alloc] init];
    [arrCheckList addObject:oneContact];
    [[MyClass getInstance].personMarkList addObject:oneContact];
    
    composeMessageViewController *view = [[composeMessageViewController alloc] initWithContact:arrCheckList];
    view.isSendBack = YES;
    view.sendBackDic = oneContact;
    [self.navigationController pushViewController:view animated:YES];
    [view release];
    [arrCheckList release];
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    UIView* selfview = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
    selfview.backgroundColor = [UIColor colorWithRed:219.0f/255.0f green:226.0f/255.0f blue:237.0f/255.0f alpha:1];
    self.view = selfview;
    [selfview release];
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(popToRootView)] autorelease];
    
    UIBarButtonItem* rightBar = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStyleBordered target:self action:@selector(setTableEdit:)];
    self.navigationItem.rightBarButtonItem = rightBar;
    [rightBar release];
    
    UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 375) style:UITableViewStylePlain];
    self.table = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = [UIColor colorWithRed:0.859f green:0.886f blue:0.929f alpha:1.0f];
    tableView.tag = TABLEVIEWTAG;
    [self.view addSubview:tableView];
    [tableView release];
    
    containerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 40, 320, 40)];
    
    textView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(1, 2, 250, 40)];
    textView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    textView.backgroundColor = [UIColor clearColor];
    textView.minNumberOfLines = 1;
    textView.maxNumberOfLines = 4;
    textView.returnKeyType = UIReturnKeyDefault;
    textView.font = [UIFont systemFontOfSize:15.0f];
    textView.delegate = self;
    textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    
    [self.view addSubview:containerView];
    
    UIImage *rawEntryBackground = [UIImage imageNamed:@"MessageEntryInputField.png"];
    UIImage *entryBackground = [rawEntryBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *entryImageView = [[[UIImageView alloc] initWithImage:entryBackground] autorelease];
    entryImageView.frame = CGRectMake(5, 0, 248, 40);
    entryImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    UIImage *rawBackground = [UIImage imageNamed:@"MessageEntryBackground.png"];
    UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:background] autorelease];
    imageView.frame = CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    [containerView addSubview:imageView];
    [containerView addSubview:textView];
    [containerView addSubview:entryImageView];
    
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackgroun = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.backgroundColor = [UIColor clearColor];
    sendBtn.frame = CGRectMake(containerView.frame.size.width-69,  8, 63, 27);
    sendBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    
    [sendBtn setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [sendBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [sendBtn setBackgroundImage:selectedSendBtnBackgroun forState:UIControlStateSelected];
    [containerView addSubview:sendBtn];
    containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    showChoose=NO;
    
    UIButton* composeMsgBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    composeMsgBtn.backgroundColor = [UIColor clearColor];
    [composeMsgBtn addTarget:self action:@selector(goToComposeMsg) forControlEvents:UIControlEventTouchUpInside];
    [containerView addSubview:composeMsgBtn];
    [composeMsgBtn release];
    
    popTipView = [[UIView alloc] initWithFrame:CGRectMake(90, 50, 140, 40)];
    popTipView.layer.cornerRadius = 6;
    popTipView.layer.masksToBounds = YES;
    popTipView.backgroundColor = [UIColor blackColor];
    popTipView .alpha = 0.0f;
    
    UILabel* popLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 140, 40)];
    popLabel.tag = 20;
    popLabel.textAlignment = UITextAlignmentCenter;
    popLabel.backgroundColor = [UIColor blackColor];
    popLabel.font = [UIFont systemFontOfSize:14.0];
    popLabel.textColor = [UIColor whiteColor];
    popLabel.text = @"发送成功";
    [popTipView addSubview:popLabel];
    [popLabel release];
    
    [self.view addSubview:popTipView];
}

-(void)popSendMsgRetView:(int)code {
    UILabel* contentLabel = (UILabel*)[popTipView viewWithTag:20];
    if (code == 0) {
        contentLabel.text = @"发送成功";
    }
    else{
        contentLabel.text = @"发送失败";
    }
    popTipView.frame = CGRectMake(90, containerView.frame.origin.y -50, 140, 40);
    popTipView.alpha = 0.8f;    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration: 2.0];
    
    popTipView.alpha = 0.0f;
    
    [UIView commitAnimations];
}

-(int)sendmyMessage{
    int ret = 1;
    NSMutableArray * arrContacts;
    arrContacts = [[NSMutableArray alloc] init];
    if ([strMark length]<=0) {
        return ret;
    }
    [arrContacts addObject:strMark];
    if (arrContacts) {
        NSString *str =  textView.text;
        if ([arrContacts count]>0)
        {
            NSDictionary* retDic = [[MyClass getInstance] sendMessage:str _to:arrContacts];
            ret = [(NSNumber*)[retDic objectForKey:@"code"] intValue];
            textView.text=@"";
        }
    }
    [arrContacts release];
    return ret;
}
-(void)sendMessage{
    [textView resignFirstResponder];
    int code = [self sendmyMessage];
    
    [self popSendMsgRetView:code];
    
    NSDictionary * ret = [[MyClass getInstance] getNewMessages:strMark startAt:0 limit:15];
    if ([[ret objectForKey:@"total"] intValue] > 0) {
        self.messageArray = [ret objectForKey:@"list"];
        if (messageArray) {
            startAt = [messageArray count];
        }
    }
    [self resetUI];
    showChoose = NO;
    [table reloadData];
}
-(void)resignTextView{
    [textView resignFirstResponder];
}
-(void)transmitMessage{
    [textView resignFirstResponder];
    NSMutableString * mutableStr= [[NSMutableString alloc] init];
    for (NSDictionary * dict in messageArray) {
        if ([[dict objectForKey:@"check"] isEqualToString:@"true"]) {
            [mutableStr appendString:[dict objectForKey:@"content"]];
            [mutableStr appendString:@"        "];
        }
    }
    composeMessageViewController* freeMessageController = [[composeMessageViewController alloc] init];
    freeMessageController.smsText = mutableStr;
    freeMessageController.subSend = YES;
    [self.navigationController pushViewController:freeMessageController animated:YES];
    [freeMessageController release];
    [mutableStr release];
}

-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    startAt = 0;
    MyClass *gs = [MyClass getInstance];
    NSDictionary * ret = [gs getNewMessages:self.strMark startAt:startAt limit:15];
    if ([[ret objectForKey:@"total"] intValue] > 0) {
        NSArray * arr = [ret objectForKey:@"list"];
        if (self.messageArray ) {
            [self.messageArray removeAllObjects];
        }
        else
        {
            self.messageArray= [[NSMutableArray alloc] init];   
        }
        [self.messageArray addObjectsFromArray:arr];
        startAt=[arr count];
    }
    [table reloadData];
    if ([messageArray count]<=0)
        self.title  = @"往来消息";
    else
        self.title = [[messageArray objectAtIndex:0] objectForKey:@"personShowName"];
//    table.contentOffset = CGPointMake(0, table.frame.size.height-64) ;
    if (messageArray)
        if ([messageArray count]>0)
    [table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow: [messageArray count] -1  inSection:0] 
           atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
    [super viewWillDisappear:animated];
}
#pragma mark keyboard响应函数
-(void) keyboardWillShow:(NSNotification*)note{
    //get keyboard size and location
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    //nees to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    //get a rect for the textView frame
    CGRect containerFrame = containerView.frame;
    containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height) + self.tabBarController.tabBar.frame.size.height;
    
    //table view
    UITableView *tableView = (UITableView *)[self.view viewWithTag:TABLEVIEWTAG];
    
    //animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    //set views with new info
    containerView.frame = containerFrame;
    self.view.center = CGPointMake(160, 160); 
    tableView.frame = CGRectMake(0.0f, 0.0f, 320.0f, containerFrame.origin.y);
    //commit animations
    [UIView commitAnimations];
    
    if([messageArray count])
		[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(messageArray.count-1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

-(void) keyboardWillHide:(NSNotification*)note{
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    self.view.center = CGPointMake(160, 208);     
    //get a rect for the textView frame
    CGRect containerFrame = containerView.frame;
    containerFrame.origin.y = self.view.bounds.size.height - containerFrame.size.height;
    
    //tableView
    UITableView *tableView = (UITableView *)[self.view viewWithTag:TABLEVIEWTAG];
	
    
    //animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationCurve:[curve intValue]];
    [UIView setAnimationDuration:[duration doubleValue]];
    
    //set view with new info
    containerView.frame = containerFrame;
    
    tableView.frame = CGRectMake(0.0f, 0.0f, 320.0f, containerFrame.origin.y);
    
    //commit animations
    [UIView commitAnimations];
}

#pragma mark HPGrowingTextView delegate
- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect r = containerView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
	containerView.frame = r;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [messageArray count];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSString *chat = [[messageArray objectAtIndex:[indexPath row]] objectForKey:@"content"];
    UIFont *font = [UIFont systemFontOfSize:12];
	CGSize size = [chat sizeWithFont:font constrainedToSize:CGSizeMake(150.0f, 1000.0f) lineBreakMode:UILineBreakModeCharacterWrap];
	return size.height+30.0f;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero] autorelease];        
		cell.backgroundColor = [UIColor colorWithRed:0.859f green:0.886f blue:0.929f alpha:1.0f];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
	NSDictionary *chatInfo = [messageArray objectAtIndex:[indexPath row]];
	for(UIView *subview in [cell.contentView subviews])
		[subview removeFromSuperview];
    NSString *strContent;
    strContent = [chatInfo objectForKey:@"content"];
    BOOL isSent;
    isSent = [[chatInfo objectForKey:@"isSent"] isEqualToString:@"true"];
    UIView* bubbleView = [self bubbleView:strContent from: isSent];
    CGRect bubbleFrame = bubbleView.frame;
    
    NSDate* timeDate = [chatInfo objectForKey:@"time"];
    NSDateFormatter * formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyyMMdd HH:mm"];
    
    
    UILabel* timelabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 20)];
    timelabel.textAlignment = UITextAlignmentCenter;
    timelabel.font = [UIFont systemFontOfSize:10];
    timelabel.text = [formater stringFromDate:timeDate];
    timelabel.textColor = [UIColor blackColor];
    timelabel.backgroundColor = [UIColor clearColor];
    [cell.contentView addSubview:timelabel];
    [timelabel release];
    
    [formater release];
    
    [cell.contentView addSubview:bubbleView];
    if (showChoose)
    {
        UIImageView* checkImage = [[UIImageView alloc] initWithFrame:CGRectMake(2, bubbleFrame.size.height*0.5-4, 28, 28)];
        checkImage.tag = 100;
        BOOL checked=NO;
        NSDictionary *dict = [self.messageArray objectAtIndex:indexPath.row];
        if ([[dict allKeys] containsObject:@"check"]){
            if ([[dict objectForKey:@"check"] isEqual:@"true"]) {
                checked=YES;  
            }
            
        }
        if (checked)
        {
            [checkImage setImage:[UIImage imageNamed:@"choose_on.png"]];
            //self.backgroundView.backgroundColor = [UIColor colorWithRed:223.0/255.0 green:230.0/255.0 blue:250.0/255.0 alpha:1.0];
        }
        else
        {
            [checkImage setImage:[UIImage imageNamed:@"choose.png"]];
            //self.backgroundView.backgroundColor = [UIColor whiteColor];
        }
        [cell.contentView addSubview:checkImage];
        [checkImage release];
        
    }
    else {
        cell.imageView.image=nil;
    }
    return cell;
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self creatDelView];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [textView resignFirstResponder];
    if (showChoose){
        NSMutableDictionary* infoItem = nil;
        UITableViewCell *cell = (UITableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        infoItem = [self.messageArray objectAtIndex:indexPath.row];
        BOOL checked=NO;
        if ( [[infoItem allKeys] containsObject:@"check"]){
            if ([[infoItem objectForKey:@"check"] isEqual:@"true"]) {
                [infoItem setObject:@"false" forKey:@"check"];
                if (checkCount>0)  
                    checkCount--;
                checked=NO;
            }
            else{
                [infoItem setObject:@"true" forKey:@"check"];
                checkCount++;
                checked = YES;
            }
            
        }
        else
        {
            [infoItem setObject:@"true" forKey:@"check"];
            checkCount++;
            checked=YES;
        }
        UIImageView* checkImageView = (UIImageView*)[cell.contentView viewWithTag:100];
        if (checked)
        {
            checkImageView.image = [UIImage imageNamed:@"choose_on.png"];
            //self.backgroundView.backgroundColor = [UIColor colorWithRed:223.0/255.0 green:230.0/255.0 blue:250.0/255.0 alpha:1.0];
        }
        else
        {
            checkImageView.image = [UIImage imageNamed:@"choose.png"];
            //self.backgroundView.backgroundColor = [UIColor whiteColor];
        }
        if (checkCount > 0)
        {
            NSString* str2 =[NSString stringWithFormat:@"转发短信(%d)",checkCount];
            [btnSendSms setTitle: str2 forState:(UIControlStateNormal)];
            
            NSString* str3 =[NSString stringWithFormat:@"删除短信(%d)",checkCount];
            [btnDelSms setTitle: str3 forState:(UIControlStateNormal)];
        }
        else if (checkCount == 0)
        {
            [btnSendSms setTitle: @"转发短信" forState:(UIControlStateNormal)];
            [btnDelSms setTitle: @"删除短信" forState:(UIControlStateNormal)];
        }
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    //[[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardWillHideNotification object:nil userInfo:nil];
    
}

//-(void)tableView:(UITableView *)tableView
//commitEditingStyle:(UITableViewCellEditingStyle)editStyle
//forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//	NSUInteger row = [indexPath row];
//    @try {
//        NSArray * arr =[[NSArray alloc] initWithObjects:[[messageArray objectAtIndex:row] objectForKey:@"id"], nil];
//        if ([[[[MyClass getInstance] delMessages:arr] objectForKey:@"code"] intValue]==0){
//            [self.messageArray removeObjectAtIndex:row];
//            [tableView deleteRowsAtIndexPaths:
//             [NSArray arrayWithObject:indexPath] 
//                             withRowAnimation:UITableViewRowAnimationFade];   
//        }else
//        {
//            UIAlertView* alert;
//            alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"删除失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [alert show];
//            [alert release];
//        } 
//    }
//    @catch (NSException *exception) {
//        UIAlertView* alert;
//        alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"删除失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }
//    @finally {
//
//    }
//    
//}

@end
